// SortableItem.js
"use client";

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useState } from "react";
import styles from "../index.module.scss";

export default function SortableItem({ id, index, text, isEditing, onEditStart, onEditEnd, onDelete }) {
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };
  const [inputValue, setInputValue] = useState(text);


  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`${styles.item} ${isDragging ? styles.dragging : ""}`}
    >
      <div
        className={styles.dragArea}
        ref={setActivatorNodeRef}
        {...attributes}
        {...listeners}
      >
        <div className={styles.tag}>{`P${index + 1}`}</div>
      </div>

      {isEditing && (
        <input
          className={styles.input}
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onBlur={() => onEditEnd(inputValue)}
          autoFocus
          placeholder="请输入..."
        />
      )}

      {!isEditing && (
        <div className={styles.labelAndDelBtn}>
          <div
            className={styles.label}
            title={text}
            onClick={(e) => {
              e.stopPropagation(); // ✅ 阻止冒泡，避免触发拖动
              console.log("clicked label");
              onEditStart();
            }}
          >
            {text}
          </div>
          <button
            className={styles.deleteButton}
            onClick={() => onDelete(id)}
          >
            <i className="iconfont icon-Delete"></i>
          </button>
        </div>

      )}
    </div>

  );
}
